(use 'clojure.contrib.duck-streams
     'readerManager)

(import '(java.net Socket ServerSocket)
        '(java.io PrintWriter BufferedReader InputStreamReader))

(def port 3003)
(def host "localhost")

(def file "db-1x2.db")
(def tableSizeY (get-numFields file))

(defn select-rec
  "Requests server to send all the records in the database"
  [database]
  (let [socket (Socket. host port)]
    (with-open [input (BufferedReader. (InputStreamReader. (.getInputStream socket)))
		output (PrintWriter. (.getOutputStream socket))]
      (.println output database)
      (.println output "select")
      (.flush output)
      (read-string (.readLine input))
      )))
      
(defn serialize-client
	"Converts structures into strings"
	[data]
	(binding[*print-dup* true]
  		(print-str data))
)

(defn create-new
  "Ask the server to create a record at the last position in the database"
  [database entry]
  (let [socket (Socket. host port)]
    (with-open [input (BufferedReader. (InputStreamReader. (.getInputStream socket)))
		output (PrintWriter. (.getOutputStream socket))]
      (.println output (serialize-client [database entry]))
      (.println output "create")
      (.flush output)
      )))

(defn delete-rec
  "Ask the server to delete an indicated record"
  [database recno]
  (let [socket (Socket. host port)]
    (with-open [input (BufferedReader. (InputStreamReader. (.getInputStream socket)))
		output (PrintWriter. (.getOutputStream socket))]
      (.println output (serialize-client [database recno]))
      (.println output "delete")
      (.flush output)
      ))
)

;(create-new "db-1x2" "Mayor  tableSizeY Mex 4 N 200.00 20/10/2009 Yo")
;(delete-rec "db-1x2" tableSizeY)
